package com.tang.utils;

import com.tang.system.entity.SysPermission;
import org.springframework.util.StringUtils;

import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Objects;
import java.util.function.Function;

public class TreeUtils {
    public static <T> List<T> toList(List<T> list, IdGetter<T, Object> idFunction, IdGetter<T, Object> parentFunction, IdGetter<T, Collection<T>> childrenFunction) {
        List res = CommonUtils.newList();
        if (CommonUtils.isEmpty(list)) return res;
        LinkedHashMap<Object, T> map = new LinkedHashMap<>();
        for (T t : list) {
            Object id = idFunction.apply(t);
            if (isEmpty(id)) continue;
            map.put(id, t);
        }

        for (T t : list) {
            Object parentId = parentFunction.apply(t);
            if (isEmpty(parentId)) continue;
            T parent = map.get(parentId);
            if (isEmpty(parent)) continue;

            Collection<T> children = childrenFunction.apply(parent);
            children.add(t);
        }

        for (Object o : map.keySet()) {
            T t = map.get(o);
            Object parentId = parentFunction.apply(t);
            if (isEmpty(parentId)) {
                res.add(t);
            }
        }

        return res;
    }

    public static boolean isEmpty(Object id) {
        if(Objects.isNull(id)) return true;
        if(StringUtils.isEmpty(id)) return true;
        return false;
    }



    public static interface IdGetter<T, R> extends Function<T, R> {
    }
}
